package security;


import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bouncycastle.util.encoders.Base64;

/**
 * Class used to send and receive Messages which are Base64 encoded and decoded over a TCP-Channel
 * @author Group 95
 */
public class Base64Channel implements Channel
{
    private static final Logger logger = Logger.getLogger("Base64Channel");
    
    private Channel channel;
    
    {
        logger.setLevel(Level.ALL);
    }
    
    public Base64Channel(Channel tcpChannel)
    {
        logger.log(Level.INFO, "Base64Channel tcpChannel: {0}", new Object[]{tcpChannel});        
        this.channel=tcpChannel;
    }

    @Override
    public byte[] receiveMessage() throws IOException {
        byte []bRet=decodeMessage(channel.receiveMessage());
        logger.log(Level.INFO, "receiveMessage() received: {0}", new Object[]{bRet});        
        return bRet;
    }
    
    private byte[] decodeMessage(byte[] message)
    {
        if(message!=null)
        {
            byte[] bRet=Base64.decode(message);
            logger.log(Level.INFO, "decodeMessage() decoded: {0}", new Object[]{bRet});        
            return bRet;        
        }
        return null;
    }
    
    @Override
    public byte[] reReceiveMessage() {
        return decodeMessage(channel.reReceiveMessage());
    }    

    @Override
    public void sendMessage(byte[] bMessage) throws IOException {
        logger.log(Level.INFO, "sendMessage bMessage: {0}", new Object[]{bMessage});
        bMessage=Base64.encode(bMessage);
        channel.sendMessage(bMessage);
    }

    @Override
    public void close() {
        logger.log(Level.INFO, "close()");
        channel.close();
    }
    
    /**
     * Checks if something is readable from the underlying socket
     * @return true if something can be read from the socket
     */
    public boolean receivable() throws IOException
    {
        return this.channel.receivable();
    }    
}
